package com.decheng.servlet;

import com.decheng.pojo.User;
import com.decheng.service.UserService;
import com.decheng.service.impl.UserServiceImpl;
import com.decheng.servlet.base.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @desc 用户模块
 */
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    /**
     * 返回登陆页面
     *
     * @throws IOException
     */
    public void toLoginPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 检查session中是否有用户信息
        Object loginUser = request.getSession().getAttribute("loginUser");
        if (loginUser != null) {
            // 如果用户已登陆，直接跳转到登陆成功页面
            engine.processTemplate("user/login_success", request, response);
            // 如果不结束方法的执行，会将登陆页面页渲染到登陆成功页面
            return;
        }
        engine.processTemplate("user/login", request, response);
    }

    /**
     * 处理登陆请求
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.login(username, password);
        if (user != null) {
            // 登陆成功，返回后台主页
            // 将用户信息设置到 session 中
            request.getSession().setAttribute("loginUser", user);
            engine.processTemplate("user/login_success", request, response);
        } else {
            // 登陆失败，返回登陆页，显示错误信息
            request.setAttribute("errorMsg", "用户名或密码错误");
            engine.processTemplate("user/login", request, response);
        }
    }


    /**
     * 处理注销请求
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 从 session 中移除用户信息
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser != null) {
            session.removeAttribute("loginUser");
        }

        // 重定向到首页
        response.sendRedirect(request.getContextPath() + "/index");

    }


    /**
     * 返回注册页面
     *
     * @throws IOException
     */
    public void toRegisterPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        engine.processTemplate("user/register", request, response);
    }

    /**
     * 处理注册请求
     *
     * @throws IOException
     */
    public void doRegister(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取验证码
        String code = request.getParameter("code");
        // 从 session 中获取验证码
        String checkCode = (String) request.getSession().getAttribute("checkCode");
        // 忽略大小写
        if (!code.equalsIgnoreCase(checkCode)) {
            // 不相等，返回错误信息
            request.setAttribute("codeErrorMessage", "请输入正确的验证码");
            engine.processTemplate("user/register.html", request, response);
            return;
        }


        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user, parameterMap);
            if (userService.register(user)) {
                // 注册成功，返回注册成功页面
                // 将用户信息放到 session 中
                request.getSession().setAttribute("loginUser", user);
                engine.processTemplate("user/register_success", request, response);
            } else {
                // 注册失败，用户名重复，返回注册页面，显示错误信息
                System.out.println(user.getUsername() + "用户注册失败");
                request.setAttribute("usernameErrorMessage", "用户名已重复");
                engine.processTemplate("user/register.html", request, response);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
